package com.crm.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.crm.model.mdao.SysDeptMapper;
import com.crm.model.mpojo.SysDept;
import com.crm.util.LevelUtil;

@Service
@Transactional(rollbackFor = Exception.class)
public class SysDeptServices {
	@Autowired
	SysDeptMapper sysDeptMapper;

	/**
	 * 添加部门信息
	 * 
	 * @param sysDept
	 * @return
	 */
	public Integer save(SysDept sysDept) {
		if (sysDept.getParentid().equals(0)) {
			sysDept.setLevel(0 + "");
		} else {
			SysDept parentDept = sysDeptMapper.selectByPrimaryKey(sysDept.getParentid());
			sysDept.setLevel(LevelUtil.calculateLevel(parentDept.getLevel(), parentDept.getId()));
		}
		return sysDeptMapper.insertSelective(sysDept);
	}

	/**
	 * 查询单条部门信息
	 * 
	 * @param sysDept
	 * @return
	 */
	public SysDept selectByOne(String id) {
		return sysDeptMapper.selectByPrimaryKey(1);
	}

	public List<SysDept> findAllDept() {
		return sysDeptMapper.findAllDept();
	}

	/**
	 * 修改部门信息
	 * 
	 * @param sysDept
	 * @return
	 */
	public Integer updateDept(SysDept sysDept) {
		if (sysDept.getParentid().equals(0)) {
			sysDept.setLevel(0 + "");
		} else {
			SysDept parentDept = sysDeptMapper.selectByPrimaryKey(sysDept.getParentid());
			sysDept.setLevel(LevelUtil.calculateLevel(parentDept.getLevel(), parentDept.getId()));
		}
		return sysDeptMapper.updateByPrimaryKeySelective(sysDept);
	}

}
